﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MSBTC.Model;
using Microsoft.VisualBasic;

namespace MSBTC.WinForms
{
    public partial class POForm : Form
    {
        private string Datamanip;
        private int rowselect;
        MDIParent mdipar = new MDIParent();
        PMSContext dbcontext = new PMSContext();
        PrchOrder dbpo = new PrchOrder();
        FormHelpers help = new FormHelpers();

        public POForm()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void PO_Load(object sender, EventArgs e)
        {
            RefreshDB();
            RefreshFields();
            
            //retrieve projects
            var supp = (from s in dbcontext.Suppliers
                        select s).ToList();

            if (supp.Count != 0)
            {
                foreach (var sp in supp)
                {
                    //add items in combo box
                    cmbPname.Items.Add(sp.Supplier_Name);
                }
            }
            else
            {
                MessageBox.Show("There are no Suppliers retrieved, please add new Supplier in Supplier Information in main menu", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            //Requisition
            int ctr = 0;
            var req = (from itm in dbcontext.Requests
                        select itm).ToList();
            if (req.Count != 0)
            {
                foreach (var itm in req)
                {
                    if (cmbReq.Items.Contains(itm.Requisitionid) == false)
                    {
                        cmbReq.Items.Add(itm.Requisitionid);
                        
                    }
                    ctr = +itm.Requisitionid;
                }
               
            }
            else
            {
                MessageBox.Show("There are no Requisition yet, Click the link above to create new requisition", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

        }

        #region functions
        private void RefreshDB()
        {
            var proj = (from pj in dbcontext.Suppliers
                        where pj.Supplier_Name == cmbPname.SelectedItem
                        select pj).SingleOrDefault();
            if (proj != null)
            {
                //retrieve all data in Purchase order
                var purch = (from p in dbcontext.PurchOrder
                             where p.Supplierid_FK == proj.Supplierid_PK
                             select p).ToList();

                LVPO.Items.Clear();
                if (purch != null)
                {
                    foreach (var sqlpo in purch)
                    {
                        //add items in Listview box using the LINQ

                        ListViewItem lvitems = LVPO.Items.Add(sqlpo.poid_PK.ToString());
                        lvitems.SubItems.Add(proj.Supplier_Name.ToString());
                        lvitems.SubItems.Add(sqlpo.Requisitionid.ToString());
                    }
                }
            }

            var req = (from itm in dbcontext.Requests
                       select itm).ToList();
            if (req.Count != 0)
            {
                foreach (var itm in req)
                {
                    if (cmbReq.Items.Contains(itm.Requisitionid) == false)
                    {
                        cmbReq.Items.Add(itm.Requisitionid);
                    }
                }
            }

            var por = (from p in dbcontext.PurchOrder
                       orderby p.poid_PK descending
                       select p).Take(1).SingleOrDefault();
            if (por != null)
            {
                lblPo.Text = "PO" + Convert.ToString(por.poid_PK + 1);
            }
            else
            {
                lblPo.Text = "PO1";
            }
        }

        private void ClearFields()
        {
            txtID.Clear();
            cmbReq.SelectedIndex = 0;
            cmbPname.SelectedIndex = 0;
            LVReq.Items.Clear();
        }

        private void DisableFields()
        {          
            cmbReq.Enabled = false;
        }

        private void EnableFields()
        {
            cmbReq.Enabled = true;
            cmbPname.Enabled = true;;
        }

        private void RefreshFields()
        {
            DisableFields();
            ClearFields();
            RefreshDB();

            btnNew.Enabled = true;
            btnDel.Enabled = false;
            btnSave.Enabled = false;
            btnEdit.Enabled = false;
        }
        #endregion

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearFields();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshFields();
            LVPO.Enabled = true;
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            Datamanip = "Add";

            EnableFields();
            ClearFields();

            btnSave.Enabled = true;
            btnNew.Enabled = false;
            LVPO.Enabled = false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Datamanip = "Edit";

            EnableFields();

            btnSave.Enabled = true;
            btnNew.Enabled = false;
            btnDel.Enabled = false;
        }

        private void LVPO_SelectedIndexChanged(object sender, EventArgs e)
        {
            //focus the selected items
            rowselect = LVPO.FocusedItem.Index;

            //getting the information from the listview to textbox
            txtID.Text = LVPO.Items[rowselect].SubItems[0].Text;
            lblPo.Text = LVPO.Items[rowselect].SubItems[1].Text;
            cmbPname.SelectedItem = LVPO.Items[rowselect].SubItems[2].Text;
            cmbReq.SelectedItem = LVPO.Items[rowselect].SubItems[3].Text;
            

            btnDel.Enabled = true;
            btnNew.Enabled = true;
            btnSave.Enabled = false;
            btnEdit.Enabled = true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if ((cmbPname.SelectedIndex == 0) || (cmbReq.SelectedIndex == 0))
            {
                MessageBox.Show("Please select Requisition ID and Project Name", "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
          
            else
            {
                if (Datamanip == "Add")
                { 
                    int rid = Convert.ToInt32(cmbReq.SelectedItem.ToString());
                    // retrieve data with the same supplier name to get the Supplierid_PK
                    var supp = (from sp in dbcontext.Suppliers
                                where sp.Supplier_Name == cmbPname.SelectedItem
                                select sp).SingleOrDefault();
                    //retrieve data of purchase order
                    var add = (from p in dbcontext.PurchOrder
                               where p.Supplierid_FK == supp.Supplierid_PK &&
                               p.Requisitionid == rid
                               select p).SingleOrDefault();

                    //test if the retrieve data has an existing data
                    if (add == null)//yes
                    {

                        dbpo.Supplierid_FK = supp.Supplierid_PK;
                        dbpo.POnum = lblPo.Text;
                        dbpo.Requisitionid = rid;
                        //save to database
                        dbcontext.Entry(dbpo).State = EntityState.Added;
                        dbcontext.SaveChanges();

                        MessageBox.Show("Successfully Saved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();
                    }
                    else //if it is existing data
                    {
                        DialogResult YN = MessageBox.Show("Item already exist, do you want to replace it?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (YN == DialogResult.Yes)
                        {
                            
                            //find ID of the same item name
                            var replace = dbcontext.PurchOrder.Find(add.poid_PK);

                            replace.Supplierid_FK = supp.Supplierid_PK;
                            replace.Requisitionid = rid;
                            //Modify data
                            dbcontext.Entry(replace).State = EntityState.Modified;
                            dbcontext.SaveChanges();

                            MessageBox.Show("Successfully Modified.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            RefreshFields();
                            RefreshDB();
                        }
                            
                    }
                    LVPO.Enabled = true;
                }

                else if (Datamanip == "Edit")
                {

                    DialogResult YN = MessageBox.Show("Do you want to replace it?", "Modify", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (YN == DialogResult.Yes)
                    {
                        int rid = Convert.ToInt32(cmbReq.SelectedItem.ToString());
                        //find ID of the same item name
                        var replace = dbcontext.PurchOrder.Find(Convert.ToInt32(txtID.Text));

                        var supp = (from p in dbcontext.Suppliers
                                    where p.Supplier_Name == cmbPname.SelectedItem
                                    select p).SingleOrDefault();

                        replace.Supplierid_FK = supp.Supplierid_PK;
                        replace.Requisitionid = rid;
                        //Modify data
                        dbcontext.Entry(replace).State = EntityState.Modified;
                        dbcontext.SaveChanges();

                        MessageBox.Show("Successfully Modified.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        RefreshFields();
                        RefreshDB();
                    }
                }

                LVPO.Enabled = true;
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            DialogResult YN = MessageBox.Show("Do you want to Delete it?", "Deleting", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (YN == DialogResult.Yes)
            {
                var del = dbcontext.PurchOrder.Find(Convert.ToInt32(txtID.Text));//get the same ID of purchase order to delete
                if (del != null)
                {
                    //delete the ID selected
                    dbcontext.Entry(del).State = EntityState.Deleted;
                    dbcontext.SaveChanges();
                }
                RefreshFields();
                RefreshDB();
            }
        }

        private void LLCreate_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            RequisitionForm rform = new RequisitionForm();

            rform.Show();
        }

        private void cmbReq_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbReq.SelectedIndex != 0)
            {
                int rid = Convert.ToInt32(cmbReq.SelectedItem);
                //retrieve all data in Purchase order
                var req = (from r in dbcontext.Requests
                           where r.Requisitionid == rid
                           select r).ToList();

                LVReq.Items.Clear();
                if (req != null)
                {
                    foreach (var sqlpo in req)
                    {


                        ListViewItem lvitems = LVReq.Items.Add(sqlpo.MaterialName.ToString());
                        lvitems.SubItems.Add(sqlpo.Quantity.ToString());
                        lvitems.SubItems.Add(sqlpo.Unit.ToString());

                        //var sup = (from s in dbcontext.Suppliers
                        //           where s.Supplierid_PK == sqlpo.p
                        //           select s).SingleOrDefault();
                        //if (sup != null)
                        //{
                        //    lvitems.SubItems.Add(sup.Supplier_Name.ToString());
                        //}

                    }
                }
            }
        }

        private void cmbPname_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPname.SelectedIndex != 0)
            {
                var supp = (from pj in dbcontext.Suppliers
                            where pj.Supplier_Name == cmbPname.SelectedItem
                            select pj).SingleOrDefault();
                if (supp != null)
                {
                    //retrieve all data in Purchase order
                    var purch = (from p in dbcontext.PurchOrder
                                 where p.Supplierid_FK == supp.Supplierid_PK
                                 select p).ToList();

                    LVPO.Items.Clear();
                    if (purch != null)
                    {
                        foreach (var sqlpo in purch)
                        {
                            //add items in Listview box using the LINQ
                            ListViewItem lvitems = LVPO.Items.Add(sqlpo.poid_PK.ToString());
                            lvitems.SubItems.Add(sqlpo.POnum.ToString());
                            lvitems.SubItems.Add(supp.Supplier_Name.ToString());
                            lvitems.SubItems.Add(sqlpo.Requisitionid.ToString());
                        }
                    }
                }
            }
        }
    }
}
